﻿using System;
using System.Collections.Generic;
using System.Web;
using WAD.WEB.AppCode;
using WAD.DAL;
using WAD.Model;
using QD.Utils;
using GL.Tools;
using WAD.BLL;
using System.Text;

namespace WAD.WEB.Admin.Ajax
{
    /// <summary>
    /// User 的摘要说明
    /// </summary>
    public class User : AdminAjax
    {
        public override void AjaxMethodDispatch(String identity)
        {
            switch (identity)
            {
                case "getlist_agent": this.GetList_Agent(); break;
                case "getlist": this.GetList(); break;
                case "login": this.Login(); break;
                case "editpwd": this.EditPwd(); break;
                case "getdetail": this.GetDetail(); break;
                case "getuserversion": this.GetUserVersion(); break;
                case "getname": this.Getname(); break;
                case "getlist_fanli": this.GetList_FanLi(); break;
                case "fl_setting": this.FL_Setting(); break;
                case "fl_setting_yy": this.FL_Setting_YY(); break;
                case "getyunying": this.GetYunYing(); break;
                case "setmoney": this.SetMoney(); break;
            }
        }
        /// <summary>
        /// 客户列表
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void GetList_Agent()
        {
            int page = Parse.Int("page_index", 1);//当前页
            UserBLL bll = new UserBLL();
            PageData pg = bll.GetList_Agent(Parse.Int("agentid", 0), Parse.String("nick_name"), Parse.String("name"), Parse.Int("id", 0), Parse.String("phone"), Parse.String("email"), Parse.String("version_id", ""), page, 20);
            if (pg.itemCount == 0)
                DataEmpty();
            Success(pg);
        }

        /// <summary>
        /// 用户列表
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void GetList()
        {
            int pageIndex = Parse.Int("page_index", 1);//当前页
            MUser m = new MUser()
            {
                id = Parse.Int("userid", 0),
                agentid = Parse.Int("agentid", 0),
                phone = Parse.String("phone"),
                nick_name = Parse.String("nick_name"),
                name = Parse.String("name")
            };
            PageData pg = DaoUser.GetList(pageIndex, 20, m);
            if (pg.itemCount == 0)
                DataEmpty();
            else
                Success(pg);
        }

        /// <summary>
        /// 登陆
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void Login()
        {
            int loginType = Parse.Int("login_type", 0);//登陆方式
            if (loginType == 0)
            {
                ParamError();
            }

            MUser m = new MUser();
            m.login_type = loginType;


            //站内注册
            String name = Parse.String("name");//用户名
            String pwd = Parse.String("pwd");//密码

            if (String.IsNullOrEmpty(name) || String.IsNullOrEmpty(pwd))
            {
                ParamError();
            }


            m.name = name;
            m.pwd = StringHelper.MD5Encrypt(pwd);



            //登陆数据

            Dictionary<string, object> model = WAD.DAL.Admin.User.Login(m.name, m.pwd);
            if (model != null && model["id"] != DBNull.Value)
            {
                Success(model);
            }
            else
            {
                JsonResult(Message.Code.FAIL, Message.Msg.FAIL);
            }
        }

        /// <summary>
        /// 修改客户密码
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void EditPwd()
        {
            int user_id = Parse.Int("user_id", 0);
            string pwd = Parse.String("pwd", "");   //密码
            string pwd2 = Parse.String("pwd2", "");

            MUser m = DaoUser.GetEntity(user_id);
            if (m == null)
                JsonResult(11, "会员不存在");

            //login_type 1 用户名,2 QQ, 3 微信, 4 手机
            if (m.login_type.Value == 2 || m.login_type.Value == 3)
                JsonResult(11, "不能修改QQ或微信登录的密码");

            if (DaoUser.ModifyPwd(user_id, m.login_type.Value, StringHelper.MD5Encrypt(pwd)))
                Success();
            Fail();
        }

        /// <summary>
        /// 用户详细信息
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void GetDetail()
        {
            //IsLogin();
            int userid = Parse.Int("user_id", 0);
            if (userid < 1)
                ParamError();
            Dictionary<string, object> model = DaoUser.GetDetail(userid, "");
            if (model != null)
            {
                model["ad_balance"] = DaoUser.BalanceDncode(model["ad_balance"], WJXConfig.EncryptConfig.DES_KEY);
                model["shared_balance"] = DaoUser.BalanceDncode(model["shared_balance"], WJXConfig.EncryptConfig.DES_KEY);
            }
            Success(model);
        }

        /// <summary>
        /// 用户详细信息
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void GetUserVersion()
        {
            int userid = Parse.Int("user_id", 0);
            Success(DaoUser.GetDetail(userid, ""));

        }
        /// <summary>
        /// 用户详细信息
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void Getname()
        {
            string name = Parse.String("name");
            Success(WAD.DAL.Admin.User.GetEntityByName(name));

        }


        #region 返利
        [QD.Web.Ajax.AjaxMethod]
        void GetList_FanLi()
        {
            int pageIndex = Parse.Int("page", 1);//当前页
            int type = Parse.Int("type", 0);// 1代理商返利 2 运营商返利
            if (type < 1 || type > 2)
                ParamError();

            StringBuilder sb = new StringBuilder();
            if (type == 1)
                sb.Append("discount>0");            //代理商

            if (type == 2)
                sb.Append("yunying_discount>0");    //运营商

            if (!string.IsNullOrEmpty(Parse.String("userid")))
                sb.AppendFormat(" and id={0}", Parse.Int("userid", 0));

            if (!string.IsNullOrEmpty(Parse.String("nick_name")))
                sb.AppendFormat(" and nick_name like '%{0}%'", QD.WX.Utill.Util.FilterSql(Parse.String("nick_name")));

            PageData pg = DaoUser.GetListPage("*,(select count(1) from [user] b where b.agentid=a.id) as count,(select sum(amount) from fc_record where fc_record.user_id=a.id and fc_record.modelid=2) as fl_money", "id desc", pageIndex, 20, sb.ToString(), "[user] a");
            if (pg.itemCount == 0)
                DataEmpty();
            else
                Success(pg);
        }

        [QD.Web.Ajax.AjaxMethod]
        void FL_Setting()
        {
            int id = Parse.Int("user_id", 0);
            int discount = Parse.Int("discount", 0);
            int yunying_agentid = Parse.Int("yunying_agentid", 0);
            if (id < 1 || discount < 0 || discount > 100)
                ParamError();

            Dictionary<string, object> dic = DaoUser.GetDetail(id, "discount,yunying_discount,yunying_agentid");
            if (dic == null)
            {
                dic = new Dictionary<string, object>();
                dic["discount"] = 0;
                dic["yunying_discount"] = 0;
                dic["yunying_agentid"] = 0;
            }

            int count = DaoUser.ExecuteNonQuery(string.Format("update [user] set discount={0},yunying_agentid={1} where id={2}", discount, yunying_agentid, id));
            if (count > 0)
            {
                DAOLog.Add(string.Format("设置返利,原参数【微街秀ID:{0},返利比例:{1},运营比例:{2},运营商:{3}】", id, dic["discount"], dic["yunying_discount"], dic["yunying_agentid"]), adminId);
                Success();
            }
            else
                JsonResult(11, "用户不存在");
        }
        [QD.Web.Ajax.AjaxMethod]
        void FL_Setting_YY()
        {
            int id = Parse.Int("user_id", 0);
            int discount = Parse.Int("discount", 0);
            if (id < 1 || discount < 0 || discount > 100)
                ParamError();

            int count = DaoUser.ExecuteNonQuery(string.Format("update [user] set yunying_discount={0} where id={1}", discount, id));
            if (count > 0)
                Success();
            else
                JsonResult(11, "用户不存在");
        }

        [QD.Web.Ajax.AjaxMethod]
        void GetYunYing()
        {
            PageData pg = DaoUser.GetList(100, "isnull(yunying_discount,0)>0", "[user]", "id,nick_name", "id desc");
            Success(pg);
        }
        #endregion


        /// <summary>
        /// 给会员充值
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void SetMoney()
        {
            int user_id = Parse.Int("user_id", 0);
            int direction = Parse.Int("direction", 0);
            decimal money = Parse.Decimal("amount", 0);
            string name = Parse.String("name", "");
            string remarks = Parse.String("remarks", "");

            if (user_id < 1 || direction < 1) ParamError();
            if (!CheckCaiWu())
            {
                JsonResult(11, "你没有此权限");
                return;
            }
            
            Dictionary<string, object> item = DaoUser.GetDetail(user_id, "");
            if (item == null)
                JsonResult(11, "会员不存在");

            decimal balance = DaoUser.BalanceDncode(item["ad_balance"], WJXConfig.EncryptConfig.DES_KEY);

            //更新余额(收入：money是>0，支出: money是<0)
            int count = DaoUser.UpdateBalance(user_id, balance + money, 1);
            //添加记录
            InsertDetail(user_id, money, balance + money, direction, remarks);
            if (count > 0)
                Success();
            Fail();
        }

        void InsertDetail(int userid, decimal amount, decimal banlance, int direction, string remarks)
        {
            MFCRecord m = new MFCRecord() { user_id = userid, amount = amount, balance = banlance, direction = direction, orderid = 0, article_id = 0, ip = Request.UserHostAddress, remark = remarks };
            DAOFCRecord.Add(m);
        }
    }
}